﻿using System;

namespace GameFrameWork
{
    public class LoadAssetAwaiter : IAwaiter<LoadAssetAwaiter, object>
    {
        public bool IsCompleted { get; set; }

        public string AssetName { get; private set; }
        public object Asset { get; private set; }

        public bool IsUnload { get; private set; }
        public bool IsLoading { get; private set; }
        public int Priority { get; private set; }
        public Type AssetType { get; private set; }

        protected Action continuation = null;

        public event Action<bool> OnFinish;

        public LoadAssetAwaiter(string assetName, int priority = 0, Type assetType = null)
        {
            AssetName = assetName;
            Priority = priority;
            AssetType = assetType;
        }

        public LoadAssetAwaiter GetAwaiter()
        {
            return this;
        }

        public void OnCompleted(Action continuation)
        {
            if (IsCompleted || Asset != null)
            {
                continuation?.Invoke();
                return;
            }
            this.continuation += continuation;
            if (IsLoading)
            {
                return;
            }
            IsLoading = true;
            //GameEntry.Resource.LoadAsset(AssetName, AssetType, Priority,
            //    new GameFramework.Resource.m_LoadAssetCallbacks(OnLoadSuccess, OnLoadFailed), null
            //);
        }

        protected void OnLoadSuccess(string assetName, object asset, float duration, object userData)
        {
            Asset = asset;
            IsLoading = false;
            IsCompleted = true;
            if (IsUnload)
            {
                Unload();
            }
            continuation?.Invoke();
            continuation = null;
            OnFinish?.Invoke(true);
        }

        //protected void OnLoadFailed(string assetName, GameFramework.Resource.LoadResourceStatus status, string errorMessage, object userData)
        //{
        //    UnityEngine.Debug.LogWarning($"[OnLoadFailed] {assetName}, {status}, {errorMessage}");
        //    IsLoading = false;
        //    IsCompleted = true;
        //    continuation?.Invoke();
        //    continuation = null;
        //    OnFinish?.Invoke(false);
        //}

        public object GetResult()
        {
            return Asset;
        }

        public void Unload()
        {
            IsUnload = true;
            if (Asset != null)
            {
                //GameEntry.Resource.UnloadAsset(Asset);
                //GameEntry.Resource.UnloadAsset(AssetName);
            }
            Asset = null;
        }
    }
}


